var payId;
$(function () {
    var singleTimer
    let contract_id = $('#contract_id').text()
    let one_pay = $("#onePay").val();
    let show_one = $("#showOne").val();
    // 判断是否收藏
    isCollect(contract_id)
    // 相关文档
    aboutDoc(contract_id)
    //top下载
    getTop(12)
    // 是否VIP
    if (is_vip) {
        // 显示继续阅读
        $('#not-vip-read').hide()
        $('#vip-read').show()
    }
    $('#singleBuyModal').modal('hide')
    $('#singleBuyModal')[0].addEventListener('show.bs.modal', showSingleBuyModal())
})

/**
 * 单次购买
 * @param type
 */
function onePay(type){
    let token = localStorage.getItem(TOKEN)
    let contract_id = $('#contract_id').text();
    var info = localStorage.getItem(INFO);
    if(info){
        info = JSON.parse(info);
        var bd_vid =info.bd_vid;
        var keyword = info.keyword;
        var a_user = info.userid;
        var a_planid = info.planid;
        var a_unitid =info.unitid;
        var a_keywordid = info.keywordid;
    }else{
        var bd_vid = localStorage.getItem('bd_vid');
        var keyword =localStorage.getItem('keyword');
        var a_user =localStorage.getItem('a_user');
        var a_planid=localStorage.getItem('a_planid');
        var a_unitid =localStorage.getItem('a_unitid');
        var a_keywordid = localStorage.getItem('a_keywordid');
    }
    $.ajax({
        url: "/api/order/pay",
        type: "POST",
        data:{
            payid:payId,
            contract_id:contract_id,
            type:type,
            type_mode:'pcPay',
            host:'',
            return_url:'',
            bd_vid: bd_vid,
            keyword: keyword,
            userid: a_user,
            planid:a_planid,
            unitid:a_unitid,
            keywordid:a_keywordid
        },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer " + token);
        },
        success: function (res) {
            if(res.code  == 200){
                if(type =='wechat'){
                    location.href='/pay?order_no='+res.data.order_no;
                }else{
                    const div=document.createElement('divform');
                    div.innerHTML=res.data.data;
                    document.body.appendChild(div);
                    document.forms['alipay_submit'].acceptCharset='GBK';
                    document.forms['alipay_submit'].submit();
                }
            }
        }
    });
}

function showSingle(){
    let title =  $("#contractTitle").text();
    $("#payTitle").text(title);
    $.ajax({
        url: "/api/orderType/list",
        type: "GET",
        data:{type:4},
        success: function (res) {
            if(res.code == 200){
                if(res.data[0].price){
                    payId = res.data[0].id;
                    let money =  formatCurrency(res.data[0].price/100);
                    $("#payPrice").text(money);
                    $('#singleBuyModal').modal('show');
                }
            }
        }
    });
}
// 显示单篇购买事件
function showSingleBuyModal(){
    var singleTimeInt = parseInt(60);
    timer(singleTimeInt)
}
function timer(intDiff) {
    singleTimer = window.setInterval(function () {
        var day = 0,
            hour = 0,
            minute = 0,
            second = 0;//时间默认值
        if (intDiff > 0) {
            day = Math.floor(intDiff / (60 * 60 * 24));
            hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
            minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60);
            second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
        } else if (intDiff === 0) {
            timeOut()
        }
        if (minute <= 9) minute = '0' + minute;
        if (second <= 9) second = '0' + second;
        $('#minute_show_single').html('<s></s>' + minute + '分');
        $('#second_show_single').html('<s></s>' + second + '秒');
        intDiff--;
    }, 1000);
}

// 倒计时过期
function timeOut() {
    $('#singleBuyModal').modal('hide')
    clearInterval(singleTimer)
}
function getTop(limit) {
    $.ajax({
        url: "/api/index/getTop",
        type: "GET",
        data:{limit:limit},
        success: function (res) {
            let html = ''
            $(res.data).each(function (k, v) {
                html +=` <li><img src="/static/word.png">
                    <a href="/detail/${v.id}" style="margin-left:20px;">${v.title}</a>
                 </li>`;
            })
            $('#right_top').html(html);
        }
    });
}



function aboutDoc(id) {
    $.ajax({
        url: "/api/detail/aboutDoc?id=" + id,
        type: "GET",
        success: function (res) {
            let html = ''
            $(res.data).each(function (k, v) {
                html += `
                    <div class="col col-12">
                        <div class="product-layout">
                            <div class="product-thumb">
                                <div class="image">
                                    <a href="/detail/${v.id}">
                                        <img src="https://cdn.mihetong.com/${v.title_pic}" alt="${v.title}"
                                             title="${v.title}" class="img-fluid">
                                    </a>
                                </div>
                                <div class="content product-description">
                                    <div class="caption">
                                        <h4 class="product-title"><a href="/detail/${v.id}">${v.title}</a></h4>
                                        <p>页数:${v.png_count}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>      
                `
            })
            $('#bestseller-carousel').html(html)
        }
    });
}




function showHidePage(data, hide_page) {
    if (data) {
        let token = localStorage.getItem(TOKEN)
        if (!token) {
            $('#loginButton').click()
        }
        $.ajax({
            url: "/api/member/getInfo",
            type: "GET",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer " + token);
            },
            success: function (res) {
                if (res.code !== SUCCESS_CODE) {
                    $('#loginButton').click()
                    return
                }
                if (res.data.is_vip === 1) {
                    $('#read_end').hide()
                    let a = data['png_count'] - hide_page
                    for (let i = 0; i < hide_page; i++) {
                        $('#img_content').append(`
                             <img src="https://cdn.mihetong.com/${data.png[i + a]}" id="prozoom" title="${data['title']}" alt="${data['title']}" class="img-thumbnail mb-3" data-zoom-image="#">
                        `)
                    }
                } else {
                    payType();
                }
            }
        });
    }
}

function download(contract_id) {
    let token = localStorage.getItem(TOKEN)
    if (!token) {
        $('#loginButton').click()
    }
    $.ajax({
        url: "/api/member/getPath",
        type: "GET",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer " + token);
        },
        data: {
            id: contract_id,
            type: 'contract',
        },
        success: function (res) {
            if (res.code !== SUCCESS_CODE) {
                if (res.code == 4020) {
                    layer.msg(res.message);
                } else if (res.code == 4006) {
                    payType();
                } else {
                    $('#loginButton').click();
                }
            } else {
                if(res.data.path){
                    if(!res.data.title){
                        res.data.title = '未命名文档';
                    }
                    let fileExtension = res.data.path.split('.').pop();
                    let name =  res.data.title+'.'+fileExtension;
                    getFile(res.data.path,name);
                }else{
                    layer.msg("文件下载失败");
                }
            }
        }
    });
}

// 是否收藏
function isCollect(contract_id) {
    let token = localStorage.getItem(TOKEN)
    if (token) {
        $.ajax({
            url: "/api/member/isCollect?contract_id=" + contract_id,
            type: "GET",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer " + token);
            },
            success: function (res) {
                if (res.data.bool) {
                    $('#unLike').show()
                } else {
                    $('#like').show()
                }
            }
        });
    } else {
        $('#like').show()
    }
}

function like(id) {
    let token = localStorage.getItem(TOKEN)
    if (token) {
        $.ajax({
            url: "/api/member/collect?contract_id=" + id,
            type: "GET",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer " + token);
            },
            success: function (res) {
                switch (res.code) {
                    case SUCCESS_CODE:
                        $('#like').hide()
                        $('#unLike').show()
                        break;
                    default:
                        layer.msg(res.message, {icon: 0, time: 1500});
                }
            }
        });
    } else {
        $('#loginButton').click()
    }
}

function unLike(id) {
    let token = localStorage.getItem(TOKEN)
    if (token) {
        $.ajax({
            url: "/api/member/un_collect?contract_id=" + id,
            type: "GET",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer " + token);
            },
            success: function (res) {
                if (res.code === SUCCESS_CODE) {
                    $('#like').show()
                    $('#unLike').hide()
                }
            }
        });
    } else {
        $('#loginButton').click()
    }
}

